package cn.schoolwow.workflow.module.task.action.flow.common;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.workflow.entity.WorkFlowInstance;

public class GetContextFieldValueValueCommonFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        getByDefaultFieldName(flowContext);
        getByContextData(flowContext);
    }

    @Override
    public String name() {
        return "获取实例上下文数据字段值";
    }

    private void getByDefaultFieldName(FlowContext flowContext){
        WorkFlowInstance workFlowInstance = flowContext.checkInstanceData(WorkFlowInstance.class);
        String fieldName = flowContext.checkData("fieldName", String.class);

        switch (fieldName){
            case "内置变量.发起人":{
                flowContext.putReturnData("contextFieldValue", workFlowInstance.getInitiator());
                flowContext.brokenCurrentFlow("从内置变量获取");
            }break;
        }
    }

    private void getByContextData(FlowContext flowContext){
        WorkFlowInstance workFlowInstance = flowContext.checkInstanceData(WorkFlowInstance.class);
        String fieldName = flowContext.checkData("fieldName", String.class);

        if(!workFlowInstance.getContextData().containsKey(fieldName)){
            throw new IllegalArgumentException("指定字段不存在!字段名称:"+fieldName);
        }
        Object contextFieldValue = workFlowInstance.getContextData().get(fieldName);
        if(null==contextFieldValue){
            throw new IllegalArgumentException("指定字段值为空!字段名称:"+fieldName);
        }
        flowContext.putReturnData("contextFieldValue", contextFieldValue);
    }

}
